/**
 * 
 */
package com.zte.claa.inficombo.csa.app.service.rptparse.ext.gnss.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.service.rptparse.ext.gnss.GnssCommService;

/**
 * @author lyp
 *
 */
public class GnssMinaClientHandler extends IoHandlerAdapter {
	private  Logger logger = LoggerFactory.getLogger(GnssMinaClientHandler.class);
	
	private GnssCommService commSvr = null;

	public GnssMinaClientHandler(GnssCommService commSvr) {
		this.commSvr = commSvr;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("session created: " + session.getId());
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("session opened: " + session.getId());
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("session closed: " + session.getId());
		if(this.commSvr != null){
			this.commSvr.reportConnectStatus(GnssCommService.CONN_STATUS_CLOSE);
		}
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		logger.info("session idled: " + session.getId());
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("exception: " + cause.getMessage(), cause);
		if(this.commSvr != null){
			this.commSvr.reportException(cause);
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.debug("session message received: " + session.getId()+ ", msg: " + message);
		if(this.commSvr != null){			
			this.commSvr.reportMessage(message.toString());
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.info("session message sent: "+session.getId()+", msg: "+message.toString());
	}

	public void inputClosed(IoSession session) throws Exception {
		logger.info("session = "+session.getId()+": inputClosed!");
		// 避免死循环触发inputClosed()方法。
		// session.close(true);
		session.closeNow();
	}
}
